<template>
    <div>
        <el-card>
            <el-form :inline="true" class="btn">
                <el-form-item label="职位搜素">
                    <el-input placeholder="输入职位" v-model="keyWord"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="keyWord ? false : true" @click="search">搜索</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card style="margin: 10px 0;">
            <el-button type="primary" @click="addRole" icon="Plus">添加职位</el-button>

            <el-table style="margin: 10px 0;" border :data="roleInfo" @selection-change="selectChange">
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="职位名称" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180px"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" width="180px"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template #="{ row, $index }">
                        <el-button type="primary" icon="User" size="small" @click="setRole(row)">分配权限</el-button>
                        <el-button type="warning" icon="Edit" size="small" @click="eidtRole(row)">编辑</el-button>
                        <el-button type="danger" icon="Delete" size="small" @click="deleteUser(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 7]"
                :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
                @size-change="getRoleInfo(1)" @current-change="getRoleInfo" />
        </el-card>

        <el-dialog v-model="DialogVisible" :title="roleParams.id ? '更新职位' : '添加职位'" width="50%" destroy-on-close center>
            <el-form :model="roleParams" :rules="rule" ref="roleRef">
                <el-form-item label="职位名称" prop="roleName">
                    <el-input placeholder="输入职位名称" v-model="roleParams.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="DialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRoleClick">确定</el-button>
            </template>
        </el-dialog>

        <el-drawer v-model="drawer">
            <template #header>
                <h4>分配菜单和按钮权限</h4>
            </template>
            <template #default>
                <el-tree ref="tree" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id"
                    default-expand-all :default-checked-keys="selectArr" :props="defaultProps" />
            </template>

            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelClick">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, reactive, nextTick } from 'vue'
import useLayoutSettingStore from '@/store/modules/setting'
import { reqAllRole, reqAddOrUpdateRole, reqAllMenuList, reqSetPermission, reqDeleteRole } from '@/api/acl/role'
import { ElMessage } from 'element-plus';
const pageNo = ref(1)
const pageSize = ref(3)
const total = ref(0)
const roleInfo = ref([])
const keyWord = ref('')
const drawer = ref(false)
const tree = ref()
const settingStore = useLayoutSettingStore()
const DialogVisible = ref(false)
const roleRef = ref()
const menuArr = ref([])
const selectArr = ref([])
const roleParams = reactive({
    roleName: ''
})

onMounted(() => {
    getRoleInfo()
})

const getRoleInfo = async (page = 1) => {
    pageNo.value = page
    const res = await reqAllRole(pageNo.value, pageSize.value, keyWord.value)
    if (res.code == 200) {
        total.value = res.data.total
        roleInfo.value = res.data.records
    }
}

const confirmRoleClick = async () => {
    await roleRef.value.validate()
    const res = await reqAddOrUpdateRole(roleParams)
    if (res.code == 200) {
        ElMessage({ type: 'success', message: roleParams.id ? '更新成功' : '添加成功' })
        DialogVisible.value = false
        getRoleInfo(pageNo.value)
    }
}
const addRole = () => {
    DialogVisible.value = true
    nextTick(() => {
        roleRef.value.resetFields()
        Object.assign(roleParams, {
            roleName: '',
            id: 0
        })
    })
}
const eidtRole = (row) => {
    DialogVisible.value = true
    Object.assign(roleParams, row)
}

const setRole = async (row) => {
    drawer.value = true
    Object.assign(roleParams, row)
    const res = await reqAllMenuList(roleParams.id)
    if (res.code == 200) {
        menuArr.value = res.data
        selectArr.value = filterSelectArr(menuArr.value, [])
    }
}

const filterSelectArr = (data, initArr) => {
    data.forEach((item) => {
        if (item.level == 4 && item.select) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }
    })
    return initArr
}
const search = () => {
    getRoleInfo()
    keyWord.value = ''
}
const reset = () => {
    settingStore.refresh = !settingStore.refresh
}

const confirmClick = async () => {
    const roleId = roleParams.id
    const arr = tree.value.getCheckedKeys()
    const arr1 = tree.value.getHalfCheckedKeys()
    const permissionId = arr.concat(arr1)
    const res = await reqSetPermission(roleId, permissionId)
    if (res.code == 200) {
        drawer.value = false
        ElMessage({ type: 'success', message: '分配权限成功' })
        window.location.reload()
    }
}

const deleteUser = async (id) => {
    const res = await reqDeleteRole(id)
    if (res.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getRoleInfo(roleInfo.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
const defaultProps = {
    children: 'children',
    label: 'name'
}
const rule = {
    roleName: [{ required: true, trigger: 'blur' }],
}
</script>

<style scoped>
.btn {
    display: flex;
    justify-content: space-between;
    align-items: center
}
</style>